package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-hub/cache"
	"novel-hub/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var article []model.Article

	redis_key := "article_list" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Offset(offset).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	var total int64
	model.DB.Model(&model.Article{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取列表成功",
		"data":  article,
		"total": total,
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var article model.Article

	redis_key := "article_detail" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Where("id=?", id).First(&article).Debug()
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
}
